import { Button, Form,Input, Toast } from "antd-mobile"
import {FC,useState} from 'react'
import { reg } from "../util/reg"
import { useCountDown } from "ahooks"
import { foundUser, sentYzm } from "../api/user"
import { HK } from "./HuaKuai"
export const YzmCom:FC<{
    label?:string,
    name?:string,
    phone?:string,

    flagType?:boolean
}> = ({
    label='验证码',
    name="Yzm",
    phone=localStorage.getItem('phone'),

    flagType=true
})=>{
    // 倒计时初始值
    const num = 12;
    // 显示发送验证码或者倒计时
    const [flag,setFlag] = useState(true)
    // // 验证码可写选项
    // const [dis,setdis] = useState(true)
    const [show,setshow] = useState(false)
    // 倒计时初始
    const [targetDate,setTargetDate] =  useState(0)
    // ahooks倒计时
    const [countDown] = useCountDown({
        targetDate:targetDate,
        interval:1000,
        onEnd:()=>{
            setFlag(true)
        }
    })
    // 点击发送验证码
    const getYzm = async()=>{
        let res =await foundUser(phone!)    
        if(flagType){
            if(res.result){
                Toast.show({
                    content:'该用户已经存在'
                })
            // 否则发送验证码
            }else{
                // 发送验证码请求
                let res = await sentYzm(phone!)
                setFlag(false);
                setTargetDate(Date.now() + num*1000)
            }
        }else{
            if(res.result){
                let res = await sentYzm(phone!)
                if(res.data){
                    setFlag(false);

                    setTargetDate(Date.now() + num*1000)
                }
            }else{
                Toast.show({
                    content:'手机号未注册'
                })
            }
        }  
        // 如果存在数据 证明用户已经存在

        
    }
    return (
        <div>
            {show &&<HK callback={getYzm} setshow={setshow} show={show}/>}
            <Form.Item
        name={name}
        label={label}
        help='输入四位的验证码'
        rules={[
            { required: true, message: '验证码不能为空' },
            { pattern:reg.code,message:"验证码格式不正确"}
        ]}
        extra={
            flag? <Button color='primary' size="mini" onClick={()=>setshow(true)} disabled={!reg.phone.test(phone)}>发送验证码</Button> : <a>{Math.ceil(countDown/1000)}S</a>
        }
        
        >
            <Input placeholder='请输入验证码' clearable />
            
        </Form.Item>
        </div>

    )
}